import { io, Socket } from 'socket.io-client'
import { useScanStore } from '@renderer/store/pinia/scan'
import { useSystemStore } from '@renderer/store/pinia/system'
import { EnumSocketIoType } from '@renderer/types'


export class MySocketIo {
  ioInstance: Socket

  constructor(uri, opts = {
    autoConnect: false,   // 自动连接
    withCredentials: true,
    transports: ['websocket', ],
  }) {
    this.ioInstance = io(uri, opts)
    this.listenEvents()
  }

  connect() {
    console.log(`尝试连接网关服务....`)
    this.ioInstance.connect()
  }

  listenEvents() {
    this.ioInstance.on('connect', () => {
      const systemStore = useSystemStore()

    })
    this.ioInstance.on('disconnect', () => {
      console.log('disconnect')
      const systemStore = useSystemStore()
      for (const [k, v] of Object.entries(systemStore.connectStates)) {
        systemStore.connectStates[k] = false
      }
    })
    this.listenSystemEvents()
    this.listenGatewayEvents()
  }



  listenSystemEvents() {
    this.ioInstance.on('system', ({ type, data }) => {
      console.log(`收到system 信息`, type, data)
      const systemStore = useSystemStore()
      switch (type) {
        case 'scanBtnStatus':
          const { status } = data
          systemStore.scanBtnStatus = status
          break
        case 'laserCurrentPosition':
          // 这里当前的位置应该始终在合理的区间范围，而不是移到后再确认。
          const { current } = data
          systemStore.lasePosition.current = current
          break
        case 'laser':
          const { laserStatus } = data
          systemStore.laserOpen = laserStatus
          break
        case 'system_warning':
          const { systemWarningCount } = data
          systemStore.systemAlertCount = systemWarningCount
          break
        case 'test_loop':
          console.log('收到服务响应的loop信号')
          break;
        default:
          break
      }
    })
  }

  listenGatewayEvents() {
    this.ioInstance.on('gateway', (connectObj) => {
      const systemStore = useSystemStore()
      console.log(JSON.stringify(connectObj))
      for (const [k, v] of Object.entries(connectObj)) {
        console.log(k, v)
        systemStore.connectStates[k] = v
      }
    })
  }
}
